﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SGLisp;

namespace SGLib.AITree
{
    class AISeqNode : AINode
    {
        int mCurRunIndex;
        AINode mCurRuningNode;
       
        public AISeqNode(AITree tree)
        {
            mTree = tree;
        }

        public override void Load(ListNode astNode)
        {
            this.mNodeType = AINodeType.Seq;
            this.mNodeState = AINodeState.Wait;
            this.mChildrens = new List<AINode>();
            this.mCurRunIndex = -1;
            var iter = astNode.nodes.GetEnumerator();
            iter.MoveNext();
            while (iter.MoveNext())
            {
                AINode curNode = this.mTree.ParseNode((ListNode)iter.Current);
                this.mChildrens.Add(curNode);
            }
        }

        public override void OnEnter(Context context)
        {
            this.mNodeState = AINodeState.Run;
            this.mCurRunIndex = 0;
            this.mCurRuningNode = this.mChildrens[0];
            this.mCurRuningNode.OnEnter(context);
        }

        public override void Update(Context context, float dt)
        {
            if(this.mNodeState!= AINodeState.Run)
            {
                return;
            }
            AINodeState curNodeState = this.mCurRuningNode.NodeState;
            if (curNodeState == AINodeState.Finish)
            {
                this.mCurRuningNode.OnExit();
                this.mCurRunIndex++;
                if (mCurRunIndex >= this.mChildrens.Count)
                {
                    this.mNodeState = AINodeState.Finish;
                    this.OnExit();
                    return;
                }
                this.mCurRuningNode = this.mChildrens[this.mCurRunIndex];
                this.mCurRuningNode.OnEnter(context);
            }
            else if (curNodeState == AINodeState.Error)
            {
                this.mNodeState = AINodeState.Error;
            }
            this.mCurRuningNode.Update(context,dt);
            
        }
    }
}
